import React, { Component } from 'react'
import {
  View,
  StyleSheet,
  Image,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  KeyboardAvoidingView,
  Platform,
} from 'react-native'

import NavBar from '../../../components/PublicHeader';
import ImageCropPicker from 'react-native-image-crop-picker';
import RNFS from 'react-native-fs';
import getStorageValue from '../../../utils/getStorageValue';
import fetchWebApi from '../../../public/WebApi/fetchBase';
import Layer from '../../../utils/Layer';
import {
  Constant
} from '../../../public/js/constant';
import {
  POST_ADDACCOUNT,
  POST_UPDATEACCOUNT,
  POST_ALBUMINFDOATA_UPLOAD
} from '../../../public/WebApi/myInfoDataInterface/userInfoListApi';
export default class enterAccount extends Component {
  constructor(props) {
    super(props)
    const {
      name,
      filePath,
      authType,
      creditCode,
      defaultBol,
      currentAccount,
      enterBol,
      userType
    } = this.props.navigation.state.params
    this.state = {
      // 资源数据
      enterAccountBG: require("../../../assets/images/iconResources/enterAccountBG.png"),
      topTitle: "企业账户", // 头部标题
      url: null,// 营业执照地址
      onChangeName: null,// 公司名称
      onChangeCode: null,// 信用代码
      onChangeType: null,// 公司认证类型
      currentAccount: currentAccount,// 是否已认证 

      // 修改时 原本参数
      filePath: filePath,// 图片地址
      authType: authType,// 认证类型
      creditCode: creditCode,// 信用代码
      name: name,// 公司名称
      defaultBol: defaultBol,// 判断是否为修改
      enterBol: enterBol,
      userType: userType,
    };
  }

  componentDidMount = () => {
  }


  // 处理 重复点击
  repeatPressEnter = () => {
    const T = Date.now()
    if (!this.lastClickTime ||
      Math.abs(this.lastClickTime - T) > 2000) {
      this.lastClickTime = T
      // 营业执照认证
      this.enterAccountAdd()
    }
  }
  // 处理 重复点击
  repeatPressUpdate = () => {
    const T = Date.now()
    if (!this.lastClickTime ||
      Math.abs(this.lastClickTime - T) > 2000) {
      this.lastClickTime = T
      // 营业执照认证
      this.updateAccount()
    }
  }

  // 营业执照认证
  async enterAccountAdd() {
    const {
      url,
      onChangeName,
      onChangeCode,
      onChangeType,
    } = this.state
    if (
      url,
      onChangeName,
      onChangeCode,
      onChangeType
    ) {
      const res = await fetchWebApi(POST_ADDACCOUNT,
        {
          token: await getStorageValue(Constant.TOKEN),
          filePath: url,
          name: onChangeName,
          creditCode: onChangeCode,
          authType: onChangeType
        }, 'POST');
      // 认证逻辑判断
      this.enterAccountA(res)
    } else {
      Layer.showMsg("内容不能为空");
      return
    }
  }
  // 认证逻辑判断
  enterAccountA(res) {
    const {
      userType,
      currentAccount
    } = this.state
    if (res.status == 200) {
      this.props.navigation.state.params.getUserMaillistFN()
      const key = this.props.navigation.state.key
      this.props.navigation.navigate('authentications',
        {
          currentAccount: currentAccount,
          key: key,
          defaultTrue: true,
          goBackTrue: false,
          userType: userType,
          typeTrue: true
        })
    } else {
      Layer.showMsg("认证失败");
      return
    }
  }

  // 营业执照修改
  async updateAccount() {
    const {
      url,
      onChangeName,
      onChangeCode,
      onChangeType,
    } = this.state
    if (url,
      onChangeName,
      onChangeCode,
      onChangeType
    ) {
      const res = await fetchWebApi(POST_UPDATEACCOUNT,
        {
          token: await getStorageValue(Constant.TOKEN),
          filePath: url,
          name: onChangeName,
          creditCode: onChangeCode,
          authType: onChangeType
        }, 'POST');
      // 修改逻辑判断
      this.updateAccountU(res)
    } else {
      Layer.showMsg("内容不能为空");
      return
    }
  }
  // 修改逻辑判断
  updateAccountU(res) {
    const {
      currentAccount
    } = this.state
    if (res.status == 200) {
      const { navigate } = this.props.navigation;
      this.props.navigation.state.params.getBusinLicenseFN()
      const key = this.props.navigation.state.key
      navigate('authentications',
        {
          currentAccount: currentAccount,
          key: key,
          defaultTrue: false,
          goBackTrue: true
        })
    } else {
      Layer.showMsg("修改失败");
      return
    }
  }

  // 获取本地相册
  enterAccountImg = () => {
    ImageCropPicker.openPicker({
      cropping: true,
    }).then(itemimages => {
      //  获取图片类型
      const typeArr = itemimages.path.split(".")
      // 判断图片最多可选数量
      if (itemimages.length > 1) {
        Layer.showMsg("最多可上传一张");
        return
      }
      RNFS.readFile(itemimages.path, 'base64')
        .then(content => {
          // 上传七牛云 转换图片
          this.uploadDatasbase(content, typeArr[1])
        })
    })
      .catch(err => {
        Layer.showMsg('图片读取失败');
        return
      });
  }

  // 上传七牛云 转换
  async uploadDatasbase(content, type) {
    const res = await fetchWebApi(
      POST_ALBUMINFDOATA_UPLOAD,
      {
        token: await getStorageValue(Constant.TOKEN),
        fileContent: content,
        type: type
      }, 'POST');
    if (res) {
      this.setState({
        filePath: null
      })
      this.setState({
        url: res.url
      })
    }
  }

  // 公司名称
  onChangeName(text) {
    this.setState({
      onChangeName: text
    })
  }
  // 统一社会信用代码
  onChangeCode(text) {
    this.setState({
      onChangeCode: text
    })
  }
  // 公司认证类型
  onChangeType(text) {
    this.setState({
      onChangeType: text
    })
  }
  // 修改营业执照 取消
  enterAccountCancel() {
    this.setState({
      url: null,
      onChangeCode: null,
      onChangeName: null,
      onChangeType: null
    })
    this.props.navigation.goBack()
  }
  render() {
    const {
      filePath,
      authType,
      creditCode,
      name,
      defaultBol,
      enterBol,
      topTitle,
      url,
      enterAccountBG
    } = this.state
    return (

      <View style={styles.warper}>
        {/* 导航栏 */}
        <NavBar
          navigation={this.props.navigation}
          title={topTitle}
          titleColor={"#333"}
          right={defaultBol ||
            enterBol ? "取消" : ""}
          pressRight={() => {
            defaultBol || enterBol ?
              this.enterAccountCancel() : null
          }}
        />
        {/* // 点击输入框顶起效果 */}
        <KeyboardAvoidingView
          style={styles.container}
          behavior="padding"
          keyboardVerticalOffset={
            Platform.OS === "ios" ? 25 : 35
          }
        >
          <ScrollView>
            <View style={styles.enterAccountWar}>
              <Text style={styles.enterAccountText}>请上传你的营业执照</Text>
              <TouchableOpacity onPress={() => {
                // 获取本地相册
                this.enterAccountImg()
              }}>
                <View>
                  {filePath ?
                    <Image style={styles.enterAccountImg}
                      source={{ uri: filePath }} /> :
                    (url ?
                      <Image style={styles.enterAccountImg}
                        source={{ uri: url }} /> :
                      <Image style={styles.enterAccountImg}
                        source={enterAccountBG} />)}
                  <View style={styles.textBox}>
                    <Text style={styles.text}>上传营业执照</Text>
                  </View>
                </View>
              </TouchableOpacity>
              {/* 企业名称 */}
              <View style={styles.enterAccountBox}>
                <Text style={styles.enterAccountText}>企业注册名称</Text>
                <View>
                  <TextInput
                    onChangeText={inputText =>
                      this.onChangeName(inputText)}
                    style={styles.enterAccountIpt}
                    placeholder={name ?
                      name : '即营业执照上的企业名字'}
                  />
                </View>
              </View>
              {/* 信用代码 */}
              <View style={styles.enterAccountBox}>
                <Text style={styles.enterAccountText}>统一社会信用代码</Text>
                <View>
                  <TextInput
                    onChangeText={inputText =>
                      this.onChangeCode(inputText)}
                    style={styles.enterAccountIpt}
                    placeholder={creditCode ?
                      creditCode : '请填写18位统一社会信用代码'}
                  />
                </View>
              </View>
              {/* 认证类型 */}
              <View style={styles.enterAccountBox}>
                <Text style={styles.enterAccountText}>认证类型</Text>
                <View>
                  <TextInput
                    onChangeText={inputText =>
                      this.onChangeType(inputText)}
                    style={styles.enterAccountIpt}
                    placeholder={authType ?
                      authType : '请填写营业执照类型'}
                  />
                </View>
              </View>
              <View style={styles.bottomBox}>
              </View>
            </View>
          </ScrollView>
        </KeyboardAvoidingView>
        {/* 底部认证 修改按钮 */}
        <TouchableOpacity style={styles.enterAccountContainer}
          onPress={() => {
            // 认证 修改
            defaultBol || enterBol ?
              this.repeatPressUpdate() :
              this.repeatPressEnter()
          }}>
          <View style={styles.enterAccountBtn}>
            <Text style={styles.text}>{
              defaultBol || enterBol ?
                "修改认证" : "立即认证"}</Text>
          </View>
        </TouchableOpacity>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  warper: {
    flex: 1,
    position: "relative",
    backgroundColor: "#fff"
  },
  enterAccountWar: {
    paddingTop: 15,
    paddingLeft: 15,
    paddingRight: 15
  },
  enterAccountText: {
    color: "#333",
    fontSize: 18,
    marginBottom: 20
  },
  text: {
    color: "#fff",
    fontSize: 18
  },
  textBox: {
    justifyContent: "center",
    alignItems: "center",
    width: "100%",
    height: 40,
    backgroundColor: "#B3CCFF",
    borderBottomLeftRadius: 6,
    borderBottomRightRadius: 6
  },
  enterAccountContainer: {
    position: "absolute",
    bottom: 10,
    width: "100%",
    height: 40,
    paddingLeft: 15,
    paddingRight: 15,
    justifyContent: "center",
    alignItems: "center",
  },
  enterAccountBtn: {
    width: "100%",
    height: 40,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 50,
    backgroundColor: "#1890FF"
  },
  enterAccountImg: {
    width: "100%",
    height: 220,
    borderTopLeftRadius: 6,
    borderTopRightRadius: 6
  },
  enterAccountBox: {
    marginTop: 20
  },
  enterAccountIpt: {
    width: "100%",
    height: 50,
    fontSize: 16,
    color: "#666",
    paddingLeft: 15,
    borderRadius: 6,
    backgroundColor: "#f5f5f5"
  },
  bottomBox: {
    height: 100
  }
})